import { isFunction, isString, template } from "lodash-es";

// 执行slot方法，减少样板代码
export function getSlotNode(val: any, defaultValue: any = undefined) {
  return (val ? val() : defaultValue) ?? defaultValue;
}

// 判断权限，默认：是否为true，一维是或运算，二维是且运算 [或，[且]]
export function checkAuth(
  allow: undefined | string | (string | string[])[],
  allRules: string[],
  strictMode?: boolean
) {
  if (!allow || allRules?.length == 0) return !strictMode;

  if (isString(allow)) {
    allow = [allow];
  }

  return (
    allow.findIndex((item) => {
      if (isString(item)) {
        return allRules.includes(item);
      }
      return item.findIndex((e) => !allRules.includes(e)) == -1;
    }) > -1
  );
}

// 模板或字符串编译
export const renderTemplate = (value: any, parent?: {}) => {
  if (!value) return;
  if (isFunction(value)) return value;
  // @ts-ignore
  let compile = parent ? Reflect.get(parent, "__templateCompile") : undefined;
  if (!compile) {
    compile = template(value, { interpolate: /{{([\s\S]+?)}}/g });
    if (parent) Reflect.set(parent, "__templateCompile", compile);
  }

  return compile;
};

export const splitImageStr = (str?: string) => {
  return str ? str?.split(";") : [];
};

export const formatPrice = (val: number, type: "penny" | "yuan" = "yuan") => {
  return type == "yuan" ? val / 100 : val * 100;
};
